﻿/*
Copyright 2010 Shane Ng

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using java.io;
using java.util;

namespace Jeans {
    public class PrintWriterAdapter : PrintWriter {
        /**
         * The underlying character-output stream of this
         * <code>PrintWriter</code>.
         *
         * @since 1.2
         */
        protected Writer @out;

        private bool autoFlush = false;
        private bool trouble = false;
        private PrintStream psOut = null;

        public PrintWriterAdapter(Writer writer) : base(writer){
            @out = writer;
        }

        /**
         * Line separator string.  This is the value of the line.separator
         * property at the moment that the stream was created.
         */
        private String lineSeparator;

        /** Checks to make sure that the stream has not been closed */
        private void ensureOpen() {
            if (@out == null)
                throw new IOException("Stream closed");
        }

        /**
         * Flushes the stream.
         * @see #checkError()
         */
        public override void flush() {
            try {
                lock (@lock) {
                    ensureOpen();
                    @out.flush();
                }
            }
            catch (IOException x) {
                trouble = true;
            }
        }

        /**
         * Closes the stream and releases any system resources associated
         * with it. Closing a previously closed stream has no effect.
         *
         * @see #checkError()
         */
        public override void close() {
            try {
                lock (@lock) {
                    if (@out == null)
                        return;
                    @out.close();
                    @out = null;
                }
            }
            catch (IOException x) {
                trouble = true;
            }
        }

        /**
         * Flushes the stream if it's not closed and checks its error state.
         *
         * @return <code>true</code> if the print stream has encountered an error,
         *          either on the underlying output stream or during a format
         *          conversion.
         */
        public override bool checkError() {
            if (@out != null) {
                flush();
            }
            if (@out is java.io.PrintWriter) {
                PrintWriter pw = (PrintWriter)@out;
                return pw.checkError();
            }
            else if (psOut != null) {
                return psOut.checkError();
            }
            return trouble;
        }

        /**
         * Indicates that an error has occurred.
         *
         * <p> This method will cause subsequent invocations of {@link
         * #checkError()} to return <tt>true</tt> until {@link
         * #clearError()} is invoked.
         */
        protected void setError() {
            trouble = true;
        }

        /**
         * Clears the error state of this stream.
         *
         * <p> This method will cause subsequent invocations of {@link
         * #checkError()} to return <tt>false</tt> until another write
         * operation fails and invokes {@link #setError()}.
         *
         * @since 1.6
         */
        protected void clearError() {
            trouble = false;
        }

        /*
         * Exception-catching, lock output operations,
         * which also implement the write() methods of Writer
         */

        /**
         * Writes a single character.
         * @param c int specifying a character to be written.
         */
        public override void write(int c) {
            try {
                lock (@lock) {
                    ensureOpen();
                    @out.write(c);
                }
            }
            catch (InterruptedIOException x) {
                //Thread.currentThread().interrupt();
            }
            catch (IOException x) {
                trouble = true;
            }
        }

        /**
         * Writes A Portion of an array of characters.
         * @param buf Array of characters
         * @param off Offset from which to start writing characters
         * @param len Number of characters to write
         */
        public override void write(char[] buf, int off, int len) {
            try {
                lock (@lock) {
                    ensureOpen();
                    @out.write(buf, off, len);
                }
            }
            catch (InterruptedIOException x) {
                //Thread.currentThread().interrupt();
            }
            catch (IOException x) {
                trouble = true;
            }
        }

        /**
         * Writes an array of characters.  This method cannot be inherited from the
         * Writer class because it must suppress I/O exceptions.
         * @param buf Array of characters to be written
         */
        public override void write(char[] buf) {
            write(buf, 0, buf.Length);
        }

        /**
         * Writes a portion of a string.
         * @param s A String
         * @param off Offset from which to start writing characters
         * @param len Number of characters to write
         */
        public override void write(String s, int off, int len) {
            try {
                lock (@lock) {
                    ensureOpen();
                    @out.write(s, off, len);
                }
            }
            catch (InterruptedIOException x) {
                //Thread.currentThread().interrupt();
            }
            catch (IOException x) {
                trouble = true;
            }
        }

        /**
         * Writes a string.  This method cannot be inherited from the Writer class
         * because it must suppress I/O exceptions.
         * @param s String to be written
         */
        public override void write(String s) {
            write(s, 0, s.Length);
        }

        private void newLine() {
            try {
                lock (@lock) {
                    ensureOpen();
                    @out.write(lineSeparator);
                    if (autoFlush)
                        @out.flush();
                }
            }
            catch (InterruptedIOException x) {
                //Thread.currentThread().interrupt();
            }
            catch (IOException x) {
                trouble = true;
            }
        }

        /* Methods that do not terminate lines */

        /**
         * Prints a bool value.  The string produced by <code>{@link
         * java.lang.String#valueOf(bool)}</code> is translated into bytes
         * according to the platform's default character encoding, and these bytes
         * are written in exactly the manner of the <code>{@link
         * #write(int)}</code> method.
         *
         * @param      b   The <code>bool</code> to be printed
         */
        public override void print(bool b) {
            write(b ? "true" : "false");
        }

        /**
         * Prints a character.  The character is translated into one or more bytes
         * according to the platform's default character encoding, and these bytes
         * are written in exactly the manner of the <code>{@link
         * #write(int)}</code> method.
         *
         * @param      c   The <code>char</code> to be printed
         */
        public override void print(char c) {
            write(c);
        }

        /**
         * Prints an integer.  The string produced by <code>{@link
         * java.lang.String#valueOf(int)}</code> is translated into bytes according
         * to the platform's default character encoding, and these bytes are
         * written in exactly the manner of the <code>{@link #write(int)}</code>
         * method.
         *
         * @param      i   The <code>int</code> to be printed
         * @see        java.lang.Integer#toString(int)
         */
        public override void print(int i) {
            write(i.ToString());
        }

        /**
         * Prints a long integer.  The string produced by <code>{@link
         * java.lang.String#valueOf(long)}</code> is translated into bytes
         * according to the platform's default character encoding, and these bytes
         * are written in exactly the manner of the <code>{@link #write(int)}</code>
         * method.
         *
         * @param      l   The <code>long</code> to be printed
         * @see        java.lang.Long#toString(long)
         */
        public override void print(long l) {
            write(l.ToString());
        }

        /**
         * Prints a floating-point number.  The string produced by <code>{@link
         * java.lang.String#valueOf(float)}</code> is translated into bytes
         * according to the platform's default character encoding, and these bytes
         * are written in exactly the manner of the <code>{@link #write(int)}</code>
         * method.
         *
         * @param      f   The <code>float</code> to be printed
         * @see        java.lang.Float#toString(float)
         */
        public override void print(float f) {
            write(f.ToString());
        }

        /**
         * Prints a double-precision floating-point number.  The string produced by
         * <code>{@link java.lang.String#valueOf(double)}</code> is translated into
         * bytes according to the platform's default character encoding, and these
         * bytes are written in exactly the manner of the <code>{@link
         * #write(int)}</code> method.
         *
         * @param      d   The <code>double</code> to be printed
         * @see        java.lang.Double#toString(double)
         */
        public override void print(double d) {
            write(d.ToString());
        }

        /**
         * Prints an array of characters.  The characters are converted into bytes
         * according to the platform's default character encoding, and these bytes
         * are written in exactly the manner of the <code>{@link #write(int)}</code>
         * method.
         *
         * @param      s   The array of chars to be printed
         *
         * @throws  NullPointerException  If <code>s</code> is <code>null</code>
         */
        public override void print(char[] s) {
            write(s);
        }

        /**
         * Prints a string.  If the argument is <code>null</code> then the string
         * <code>"null"</code> is printed.  Otherwise, the string's characters are
         * converted into bytes according to the platform's default character
         * encoding, and these bytes are written in exactly the manner of the
         * <code>{@link #write(int)}</code> method.
         *
         * @param      s   The <code>String</code> to be printed
         */
        public override void print(String s) {
            if (s == null) {
                s = "null";
            }
            write(s);
        }

        /**
         * Prints an object.  The string produced by the <code>{@link
         * java.lang.String#valueOf(Object)}</code> method is translated into bytes
         * according to the platform's default character encoding, and these bytes
         * are written in exactly the manner of the <code>{@link #write(int)}</code>
         * method.
         *
         * @param      obj   The <code>Object</code> to be printed
         * @see        java.lang.Object#toString()
         */
        public override void print(Object obj) {
            write(obj.ToString());
        }

        /* Methods that do terminate lines */

        /**
         * Terminates the current line by writing the line separator string.  The
         * line separator string is defined by the system property
         * <code>line.separator</code>, and is not necessarily a single newline
         * character (<code>'\n'</code>).
         */
        public override void println() {
            newLine();
        }

        /**
         * Prints a bool value and then terminates the line.  This method behaves
         * as though it invokes <code>{@link #print(bool)}</code> and then
         * <code>{@link #println()}</code>.
         *
         * @param x the <code>bool</code> value to be printed
         */
        public override void println(bool x) {
            lock (@lock) {
                print(x);
                println();
            }
        }

        /**
         * Prints a character and then terminates the line.  This method behaves as
         * though it invokes <code>{@link #print(char)}</code> and then <code>{@link
         * #println()}</code>.
         *
         * @param x the <code>char</code> value to be printed
         */
        public override void println(char x) {
            lock (@lock) {
                print(x);
                println();
            }
        }

        /**
         * Prints an integer and then terminates the line.  This method behaves as
         * though it invokes <code>{@link #print(int)}</code> and then <code>{@link
         * #println()}</code>.
         *
         * @param x the <code>int</code> value to be printed
         */
        public override void println(int x) {
            lock (@lock) {
                print(x);
                println();
            }
        }

        /**
         * Prints a long integer and then terminates the line.  This method behaves
         * as though it invokes <code>{@link #print(long)}</code> and then
         * <code>{@link #println()}</code>.
         *
         * @param x the <code>long</code> value to be printed
         */
        public override void println(long x) {
            lock (@lock) {
                print(x);
                println();
            }
        }

        /**
         * Prints a floating-point number and then terminates the line.  This method
         * behaves as though it invokes <code>{@link #print(float)}</code> and then
         * <code>{@link #println()}</code>.
         *
         * @param x the <code>float</code> value to be printed
         */
        public override void println(float x) {
            lock (@lock) {
                print(x);
                println();
            }
        }

        /**
         * Prints a double-precision floating-point number and then terminates the
         * line.  This method behaves as though it invokes <code>{@link
         * #print(double)}</code> and then <code>{@link #println()}</code>.
         *
         * @param x the <code>double</code> value to be printed
         */
        public override void println(double x) {
            lock (@lock) {
                print(x);
                println();
            }
        }

        /**
         * Prints an array of characters and then terminates the line.  This method
         * behaves as though it invokes <code>{@link #print(char[])}</code> and then
         * <code>{@link #println()}</code>.
         *
         * @param x the array of <code>char</code> values to be printed
         */
        public override void println(char[] x) {
            lock (@lock) {
                print(x);
                println();
            }
        }

        /**
         * Prints a String and then terminates the line.  This method behaves as
         * though it invokes <code>{@link #print(String)}</code> and then
         * <code>{@link #println()}</code>.
         *
         * @param x the <code>String</code> value to be printed
         */
        public override void println(String x) {
            lock (@lock) {
                print(x);
                println();
            }
        }

        /**
         * Prints an Object and then terminates the line.  This method calls
         * at first String.valueOf(x) to get the printed object's string value,
         * then behaves as
         * though it invokes <code>{@link #print(String)}</code> and then
         * <code>{@link #println()}</code>.
         *
         * @param x  The <code>Object</code> to be printed.
         */
        public override void println(Object x) {
            String s = x.ToString();
            lock (@lock) {
                print(s);
                println();
            }
        }

        /**
         * A convenience method to write a formatted string to this writer using
         * the specified format string and arguments.  If automatic flushing is
         * enabled, calls to this method will flush the output buffer.
         *
         * <p> An invocation of this method of the form <tt>@out.printf(format,
         * args)</tt> behaves in exactly the same way as the invocation
         *
         * <pre>
         *     @out.format(format, args) </pre>
         *
         * @param  format
         *         A format string as described in <a
         *         href="../util/Formatter.html#syntax">Format string syntax</a>.
         *
         * @param  args
         *         Arguments referenced by the format specifiers in the format
         *         string.  If there are more arguments than format specifiers, the
         *         extra arguments are ignored.  The number of arguments is
         *         variable and may be zero.  The maximum number of arguments is
         *         limited by the maximum dimension of a Java array as defined by
         *         the <a href="http://java.sun.com/docs/books/vmspec/">Java
         *         Virtual Machine Specification</a>.  The behaviour on a
         *         <tt>null</tt> argument depends on the <a
         *         href="../util/Formatter.html#syntax">conversion</a>.
         *
         * @throws  IllegalFormatException
         *          If a format string contains an illegal syntax, a format
         *          specifier that is incompatible with the given arguments,
         *          insufficient arguments given the format string, or other
         *          illegal conditions.  For specification of all possible
         *          formatting errors, see the <a
         *          href="../util/Formatter.html#detail">Details</a> section of the
         *          formatter class specification.
         *
         * @throws  NullPointerException
         *          If the <tt>format</tt> is <tt>null</tt>
         *
         * @return  This writer
         *
         * @since  1.5
         */
        public override PrintWriter printf(String format, params Object[] args) {
            throw new NotImplementedException();
        }

        /**
         * A convenience method to write a formatted string to this writer using
         * the specified format string and arguments.  If automatic flushing is
         * enabled, calls to this method will flush the output buffer.
         *
         * <p> An invocation of this method of the form <tt>@out.printf(l, format,
         * args)</tt> behaves in exactly the same way as the invocation
         *
         * <pre>
         *     @out.format(l, format, args) </pre>
         *
         * @param  l
         *         The {@linkplain java.util.Locale locale} to apply during
         *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization
         *         is applied.
         *
         * @param  format
         *         A format string as described in <a
         *         href="../util/Formatter.html#syntax">Format string syntax</a>.
         *
         * @param  args
         *         Arguments referenced by the format specifiers in the format
         *         string.  If there are more arguments than format specifiers, the
         *         extra arguments are ignored.  The number of arguments is
         *         variable and may be zero.  The maximum number of arguments is
         *         limited by the maximum dimension of a Java array as defined by
         *         the <a href="http://java.sun.com/docs/books/vmspec/">Java
         *         Virtual Machine Specification</a>.  The behaviour on a
         *         <tt>null</tt> argument depends on the <a
         *         href="../util/Formatter.html#syntax">conversion</a>.
         *
         * @throws  IllegalFormatException
         *          If a format string contains an illegal syntax, a format
         *          specifier that is incompatible with the given arguments,
         *          insufficient arguments given the format string, or other
         *          illegal conditions.  For specification of all possible
         *          formatting errors, see the <a
         *          href="../util/Formatter.html#detail">Details</a> section of the
         *          formatter class specification.
         *
         * @throws  NullPointerException
         *          If the <tt>format</tt> is <tt>null</tt>
         *
         * @return  This writer
         *
         * @since  1.5
         */
        public override PrintWriter printf(Locale l, String format, params Object[] args) {
            throw new NotImplementedException();
        }

        /**
         * Writes a formatted string to this writer using the specified format
         * string and arguments.  If automatic flushing is enabled, calls to this
         * method will flush the output buffer.
         *
         * <p> The locale always used is the one returned by {@link
         * java.util.Locale#getDefault() Locale.getDefault()}, regardless of any
         * previous invocations of other formatting methods on this object.
         *
         * @param  format
         *         A format string as described in <a
         *         href="../util/Formatter.html#syntax">Format string syntax</a>.
         *
         * @param  args
         *         Arguments referenced by the format specifiers in the format
         *         string.  If there are more arguments than format specifiers, the
         *         extra arguments are ignored.  The number of arguments is
         *         variable and may be zero.  The maximum number of arguments is
         *         limited by the maximum dimension of a Java array as defined by
         *         the <a href="http://java.sun.com/docs/books/vmspec/">Java
         *         Virtual Machine Specification</a>.  The behaviour on a
         *         <tt>null</tt> argument depends on the <a
         *         href="../util/Formatter.html#syntax">conversion</a>.
         *
         * @throws  IllegalFormatException
         *          If a format string contains an illegal syntax, a format
         *          specifier that is incompatible with the given arguments,
         *          insufficient arguments given the format string, or other
         *          illegal conditions.  For specification of all possible
         *          formatting errors, see the <a
         *          href="../util/Formatter.html#detail">Details</a> section of the
         *          Formatter class specification.
         *
         * @throws  NullPointerException
         *          If the <tt>format</tt> is <tt>null</tt>
         *
         * @return  This writer
         *
         * @since  1.5
         */
        public override PrintWriter format(String format, params Object[] args) {
            throw new NotImplementedException();
        }

        /**
         * Writes a formatted string to this writer using the specified format
         * string and arguments.  If automatic flushing is enabled, calls to this
         * method will flush the output buffer.
         *
         * @param  l
         *         The {@linkplain java.util.Locale locale} to apply during
         *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization
         *         is applied.
         *
         * @param  format
         *         A format string as described in <a
         *         href="../util/Formatter.html#syntax">Format string syntax</a>.
         *
         * @param  args
         *         Arguments referenced by the format specifiers in the format
         *         string.  If there are more arguments than format specifiers, the
         *         extra arguments are ignored.  The number of arguments is
         *         variable and may be zero.  The maximum number of arguments is
         *         limited by the maximum dimension of a Java array as defined by
         *         the <a href="http://java.sun.com/docs/books/vmspec/">Java
         *         Virtual Machine Specification</a>.  The behaviour on a
         *         <tt>null</tt> argument depends on the <a
         *         href="../util/Formatter.html#syntax">conversion</a>.
         *
         * @throws  IllegalFormatException
         *          If a format string contains an illegal syntax, a format
         *          specifier that is incompatible with the given arguments,
         *          insufficient arguments given the format string, or other
         *          illegal conditions.  For specification of all possible
         *          formatting errors, see the <a
         *          href="../util/Formatter.html#detail">Details</a> section of the
         *          formatter class specification.
         *
         * @throws  NullPointerException
         *          If the <tt>format</tt> is <tt>null</tt>
         *
         * @return  This writer
         *
         * @since  1.5
         */
        public override PrintWriter format(Locale l, String format, params Object[] args) {
            throw new NotImplementedException();
        }



        /**
         * Appends the specified character to this writer.
         *
         * <p> An invocation of this method of the form <tt>@out.append(c)</tt>
         * behaves in exactly the same way as the invocation
         *
         * <pre>
         *     @out.write(c) </pre>
         *
         * @param  c
         *         The 16-bit character to append
         *
         * @return  This writer
         *
         * @since 1.5
         */
        public override PrintWriter append(char c) {
            write(c);
            return this;
        }

    }
}